package com.equdao.car_violation_inquiry.service.impl;

import com.alibaba.fastjson.JSON;
import com.equdao.car_violation_inquiry.dao.*;
import com.equdao.car_violation_inquiry.pojo.*;
import com.equdao.car_violation_inquiry.service.LocalService;
import com.equdao.car_violation_inquiry.utils.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 杨忠强
 * @Date: 2018/5/30 15:57
 * @Description:
 */

@Service
public class LocalServiceImpl implements LocalService {
    @Resource
    private LocalDaoMapper localDaoMapper;
    //万物
    @Resource
    private LocalViolationInfoDaoMapper localViolationInfoDaoMapper;
    //无名
    @Resource
    private LocalViolationInfoWMDaoMapper localViolationInfoWMDaoMapper;
    //万物
    @Resource
    private LocalViolationDetailDaoMapper localViolationDetailDaoMapper;
    //无名
    @Resource
    private LocalViolationDetailDaoWMMapper localViolationDetailDaoWMMapper;

    @Resource
    private HttpAPIServiceWanWu httpAPIServiceWanWu;

    @Resource
    private HttpAPIService httpAPIService;

    //万物
    @Value("${wz.token}")
    private String userToken;
    @Value("${wz.user}")
    private String user;
    @Value("${wz.api}")
    private String wwapi;
    @Value("${wz.url}")
    private String wwurl;

    //广州桓达
    @Value("${wm.username}")
    private String username;
    @Value("${wm.url}")
    private String wmurl;


    @Override
    public List<LocalBaseCarDO> findLocalBaseCar() {
        ArrayList<LocalBaseCarDO> list = localDaoMapper.findLocalBaseCar();


        return list;

    }

    @Async
    @Override
    public Integer findWWViolationInfo(List<LocalBaseCarDO> list) {
        /*根据用户请求参数查询上游*/
        for (LocalBaseCarDO baseCarDO : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("user", user);
            map.put("token", userToken);
            map.put("api", wwurl);
            map.put("cph", baseCarDO.getVehicleNo());
            map.put("cx", "02");

//String substring = str.substring(str.length()-6);


            map.put("cjh", baseCarDO.getFrameNo().substring(baseCarDO.getFrameNo().length() - 6));
            map.put("fdj", baseCarDO.getEngineNo().substring(baseCarDO.getEngineNo().length() - 6));

            //TODO  山东地区特殊 不需要添加assign
//            String provinceCode = CityCodeUtils.getProvinceCode(baseCarDO.getVehicleNo().substring(0, 1));
//            if (!"".equals(provinceCode)) {
//                map.put("assign", provinceCode);
//                System.out.println(provinceCode);
//            }
            HttpResult httpResult = null;
            System.out.println("传入的id----->:" + baseCarDO.getId());
            System.out.println("传入的车牌号--->" + baseCarDO.getVehicleNo());
            try {
                httpResult = httpAPIServiceWanWu.doPost(wwurl, map);
                String resultBody = httpResult.getBody();
                System.out.println("输出的body---" + resultBody);
                LocalViolationInfoDO localViolationInfoDO = new LocalViolationInfoDO();
                localViolationInfoDO.setCph(baseCarDO.getVehicleNo());
                localViolationInfoDO.setCjh(baseCarDO.getFrameNo());
                localViolationInfoDO.setFdj(baseCarDO.getEngineNo());
                localViolationInfoDO.setData(resultBody);
                localViolationInfoDO.setStatus(1); //1是成功   9是失败的
                localViolationInfoDaoMapper.saveViolationInfo(localViolationInfoDO);

                //解析返回来的数据 bizModel = JSON.parseObject(data,YibaoResultBizModel.class);
                ResponseUpstreamBean responseUpstreamBean = JSON.parseObject(resultBody, ResponseUpstreamBean.class);

                if (!responseUpstreamBean.getData().isEmpty()) {

                    //将查询到的数据存入明细表里
                    //TODO 这个地方可以优化    批量写入数据库
                    for (ViolationDetails details : responseUpstreamBean.getData()) {
                        LocalViolationDetailDO localViolationDetailDO = new LocalViolationDetailDO();
                        localViolationDetailDO.setCph(responseUpstreamBean.getCph());
                        localViolationDetailDO.setCjh(baseCarDO.getFrameNo());
                        localViolationDetailDO.setFdj(baseCarDO.getEngineNo());
                        localViolationDetailDO.setMsg(responseUpstreamBean.getMsg());
                        localViolationDetailDO.setWzsj(details.getWzsj());
                        localViolationDetailDO.setWzdd(details.getWzdd());
                        localViolationDetailDO.setWzxw(details.getWzxw());
                        localViolationDetailDO.setWzfk(details.getWzfk());
                        localViolationDetailDO.setWzjf(details.getWzjf());
                        localViolationDetailDO.setCsmc(details.getCsmc());
                        localViolationDetailDO.setCsdm(details.getCsdm());
                        localViolationDetailDO.setWfdm(details.getWfdm());
                        localViolationDetailDO.setClbj(details.getClbj());


                        localViolationDetailDaoMapper.saveViolationDetail(localViolationDetailDO);
                    }
                } else {
                    LocalViolationDetailDO localViolationDetailDO = new LocalViolationDetailDO();
                    localViolationDetailDO.setCph(baseCarDO.getVehicleNo());
                    localViolationDetailDO.setCjh(baseCarDO.getFrameNo());
                    localViolationDetailDO.setFdj(baseCarDO.getEngineNo());
                    localViolationDetailDO.setMsg(responseUpstreamBean.getMsg());

                    localViolationDetailDaoMapper.saveViolationDetail(localViolationDetailDO);
                }
                //加入成功   修改原数据状态为1   已查询
                if (responseUpstreamBean.getCode() != 502 && responseUpstreamBean.getCode() != 503) {
                    Integer isSuccess = localDaoMapper.updateLocalBaseCarStatusById(baseCarDO.getId());

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        //TODO 将请求到的信息保存到数据库
        //System.out.println(httpResult);
        //TODO 将保存的数据返回

        return 1; //成功
    }

    @Async
    @Override
    public Integer findWMViolationInfo(List<LocalBaseCarDO> list) {

        for (LocalBaseCarDO baseCarDO : list) {

            Map<String, Object> map = new HashMap<>();
            map.put("username", username);
            String password = MD5Utils.Md5(username).toUpperCase();
            map.put("password", password);
            map.put("carNum", baseCarDO.getVehicleNo());


            map.put("engineNumber", baseCarDO.getEngineNo());
            map.put("vin", baseCarDO.getFrameNo());
            map.put("carType", "02");
            map.put("area", baseCarDO.getVehicleNo().substring(0, 1));
            long time = System.currentTimeMillis();
            map.put("time", String.valueOf(time / 1000L));

            String signStr = username + password + baseCarDO.getVehicleNo() + baseCarDO.getEngineNo() +
                    baseCarDO.getFrameNo() + "02" + baseCarDO.getVehicleNo().substring(0, 1) +
                    String.valueOf(time / 1000L);

            System.out.println("传入id" + baseCarDO.getId());
            String sign = String.valueOf(MD5Utils.Md5(signStr));
            map.put("sign", sign);
            HttpResult httpResult = null;
            try {
                httpResult = httpAPIService.doPost(wmurl, map);


                String resultBody = httpResult.getBody();
                System.out.println("输出的body" + resultBody);
                LocalWMResponseVO localWmResponseVO = JSON.parseObject(resultBody, LocalWMResponseVO.class);


                LocalViolationInfoDO localViolationInfoDO = new LocalViolationInfoDO();

                localViolationInfoDO.setCph(baseCarDO.getVehicleNo());
                localViolationInfoDO.setCjh(baseCarDO.getFrameNo());
                localViolationInfoDO.setFdj(baseCarDO.getEngineNo());
                localViolationInfoDO.setData(resultBody);
                localViolationInfoDO.setStatus(1); //1是成功   9是失败的


                localViolationInfoWMDaoMapper.saveViolationInfo(localViolationInfoDO);

                //如果返回正常数据

                if ("success".equals(localWmResponseVO.getState())) {


                    if (!localWmResponseVO.getResult().getHistorys().isEmpty()) {

                        //将查询到的数据存入明细表里
                        //TODO 这个地方可以优化    批量写入数据库
                        for (LocalWMResponseVO.ResultEntity.HistorysEntity historysBean : localWmResponseVO.getResult().getHistorys()) {
                            LocalViolationDetailWMDO localViolationDetailDO = new LocalViolationDetailWMDO();
                            localViolationDetailDO.setCph(baseCarDO.getVehicleNo());
                            localViolationDetailDO.setCjh(baseCarDO.getFrameNo());
                            localViolationDetailDO.setFdj(baseCarDO.getEngineNo());
                            localViolationDetailDO.setMsg("Success");//返回状态
                            localViolationDetailDO.setWzsj(historysBean.getOccur_date());
                            localViolationDetailDO.setWzdd(historysBean.getOccur_area());
                            localViolationDetailDO.setWzxw(historysBean.getInfo());
                            localViolationDetailDO.setWzfk(historysBean.getMoney());
                            localViolationDetailDO.setWzjf(historysBean.getFen());
                            localViolationDetailDO.setCsmc(historysBean.getCity());
                            //localViolationDetailDO.setCsdm(details.getCsdm());
                            localViolationDetailDO.setWfdm(historysBean.getIllegal_code());

                            if ("未处理未缴款".equals(historysBean.getFine_status())) {
                                localViolationDetailDO.setClbj("1");
                            } else if ("已处理已缴款".equals(historysBean.getFine_status())) {
                                localViolationDetailDO.setClbj("3");
                            }

                            localViolationDetailDaoWMMapper.saveViolationDetail(localViolationDetailDO);
                        }
                    } else {
                        LocalViolationDetailWMDO localViolationDetailDO = new LocalViolationDetailWMDO();
                        localViolationDetailDO.setCph(baseCarDO.getVehicleNo());
                        localViolationDetailDO.setCjh(baseCarDO.getFrameNo());
                        localViolationDetailDO.setFdj(baseCarDO.getEngineNo());
                        localViolationDetailDO.setMsg("Success");
                        localViolationDetailDaoWMMapper.saveViolationDetail(localViolationDetailDO);
                    }
                    //加入成功   修改原数据状态为1   已查询

                    Integer isSuccess = localDaoMapper.updateLocalBaseCarStatusById(baseCarDO.getId());

                    System.out.println("id:" + baseCarDO.getId());
                } else if ("fail".equals(localWmResponseVO.getState())) {
                    LocalViolationDetailWMDO localViolationDetailDO = new LocalViolationDetailWMDO();
                    localViolationDetailDO.setCph(baseCarDO.getVehicleNo());
                    localViolationDetailDO.setCjh(baseCarDO.getFrameNo());
                    localViolationDetailDO.setFdj(baseCarDO.getEngineNo());
                    localViolationDetailDO.setMsg(localWmResponseVO.getError_message());
                    localViolationDetailDaoWMMapper.saveViolationDetail(localViolationDetailDO);
                    //Integer isSuccess = localDaoMapper.updateLocalBaseCarStatusById(baseCarDO.getId());

                    if ("加载超时，请稍后再试".equals(localWmResponseVO.getError_message()) || "系统出现异常!".equals(localWmResponseVO.getError_message())) {
                        System.out.println("未修改状态-----------------");

                    } else {
                        Integer isSuccess = localDaoMapper.updateLocalBaseCarStatusById(baseCarDO.getId());
                        //System.out.println("已修改状态+++++++++++++++++");

                    }


                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        return 1;
    }

}
